//
//  EFANoticeVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/29.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFANoticeVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFANoticeTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFAPjtDeviceAddVC.h"
#import "EFANoticeEditVC.h"
#import "EFANoticeDetailVC.h"

@interface EFANoticeVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *publishBarBtnItem;
@property (nonatomic, strong) EFANoticeListModel *noticeModel;
@end

static NSString *const kReuseCellId = @"EFANoticeTCell";
static NSInteger const kRequestSize = 20;

@implementation EFANoticeVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 刷新界面，主要是小红点的问题
    [self refreshWholeView];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"公告";
    NSInteger roleLevel = [EFAModel sharedInstance].loginInfo.user_info.efairyrole_level;
    if (roleLevel < 3) {
        self.navigationItem.rightBarButtonItem = self.publishBarBtnItem;
    }
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有公告" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -50.0;
}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.noticeModel.announcement_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFANoticeTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.noticeModel.announcement_list.count) {
        [cell configViewWithListItem:self.noticeModel.announcement_list[indexPath.section]];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 9.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section < self.noticeModel.announcement_list.count) {
        EFANotListItem *item = self.noticeModel.announcement_list[indexPath.section];
        [self jumpToNoticeDetailWitNotItem:item indexPath:indexPath];
    }
}
#pragma mark - event response
- (void)publishBarBtnTapped:(UIBarButtonItem *)item {
    EFANoticeEditVC *vc = [[EFANoticeEditVC alloc] init];
    vc.successHandle = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self showViewController:vc sender:nil];
}
#pragma mark - private methods
- (void)jumpToNoticeDetailWitNotItem:(EFANotListItem *)item indexPath:(NSIndexPath *)indexPath {
    EFANoticeDetailVC *vc = [[EFANoticeDetailVC alloc] init];
    vc.noticeItem = item;
    vc.successDelHandle = ^{
        [self.noticeModel removeNotListItem:item];
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.noticeModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    self.tableView.mj_footer.hidden = self.noticeModel.totalZero;
    
    [self.tableView reloadData];
    [self.tableView reloadEmptyDataSet];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestPjtDeviceListWithHeader:isHeader];
}

- (EFANoticeListModel *)noticeModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.noticeModel;
    }

    EFANoticeListModel *temp = [EFANoticeListModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.noticeModel;
    }

    if (AddMore && self.noticeModel) {
        [self.noticeModel addMoreWithData:temp];
    } else {
        self.noticeModel = temp;
    }
    return self.noticeModel;
}

#pragma mark - network request
- (void)requestPjtDeviceListWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.noticeModel.announcement_list.lastObject.efairyannouncement_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           //                           @"keyword" : @"",
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiAnnouncementList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求公告列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self noticeModelWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求公告列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)publishBarBtnItem {
    if (!_publishBarBtnItem) {
        _publishBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"发公告" style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_publishBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _publishBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
